package com.kk.springboot_002.config;

import com.kk.springboot_002.filter.JwtAuthenticationFilter;
import com.kk.springboot_002.service.MyUserDetailsService;
import com.kk.springboot_002.util.JwtUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    /**
     * 创建 JwtAuthenticationFilter 实例，并传入 MyUserDetailsService 和 JwtUtil。
     * 如果用@Autowired 注解，则会形成循环依赖。
     * @param myUserDetailsService 用户详情服务
     * @param jwtUtil              JWT 工具类
     * @return 返回 JwtAuthenticationFilter 实例。
     */
    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter(
            MyUserDetailsService myUserDetailsService,
            JwtUtil jwtUtil
    ) {
        return new JwtAuthenticationFilter(myUserDetailsService, jwtUtil);
    }

    /**
     * 配置密码编码器，用于对密码进行加密和验证。
     *
     * @return 返回 BCryptPasswordEncoder 实例。
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置身份验证提供者，会自动发现并使用定义的 UserDetailsService 和 PasswordEncoder
     *
     * @return 返回 DaoAuthenticationProvider 实例。
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception {
        http
                // 禁用CSRF
                .csrf(csrf -> csrf.disable())
                // 使用全局CORS配置（跨域）
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/api/auth/**").permitAll()
                        .requestMatchers("/api/user/delete").authenticated()
                        .anyRequest().authenticated()
                )
                // 设置为无状态会话
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 在 UsernamePasswordAuthenticationFilter 之前添加 JWT 过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://127.0.0.1:5500", "http://localhost:8090", "null"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 允许跨域请求携带任何 HTTP 请求头
        config.setAllowedHeaders(Arrays.asList("*"));
        // 允许跨域请求携带 Cookie
        config.setAllowCredentials(true);
        // 将 CORS 配置 (config) 应用于你后端的所有 API 路径（/**）
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
